package Java_Concurrency_in_Practice.c7_1_4;

import java.util.concurrent.*;

public class TimedRun3 {
    private static final ScheduledExecutorService taskExec = null;

    public static void timedRun(final Runnable r, long timeout, TimeUnit unit) throws Throwable {
        Future<?> task = taskExec.submit(r);
        try {
            task.get(timeout, unit);
        } catch (InterruptedException e) {
            // 接下来任务将被取消
        } catch (ExecutionException e) {
            // 如果在任务中抛出了异常, 那么重新抛出该异常
            throw  e.getCause();
        } catch (TimeoutException e) {
            // 接下来任务将被取消
        } finally {
            // 如果任务正在进行, 那么将被中断
            task.cancel(true);
        }
    }
}
